import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

let store = new Vuex.Store({
  state: {
      address:[]
  },
  mutations: {
      //第一个参数 state 第二个参数：
      setAddress(state,address){
          state.address = address;
      },
      //添加
      add(state,obj){
        obj.id = state.address.length+1;
        state.address.push(obj);
      },      
      //修改
      edit(state,target){
        state.address = state.address.map(item => {
            if(item.id == target.id){
                item = {...target};
            }
            return item
        })
        state.address = [...state.address];
      }
  },
  actions: {
    //异步的操作  第一个参数  和store实例有相同的方法和属性，但不是同一个对象
    getAddress({commit}){
        axios.get('/api/address').then(res => {
            commit('setAddress',res.data.data)
        })
    }
  },
  modules: {
  }
})

window.store = store;

export default store